<template>
  <div>
    <!-- 文件选择输入框 -->
    <input
      type="file"
      multiple
      accept="image/*"
      @change="handleFileChange"
      :disabled="selectedFiles.length >= 9"
    />
    <p>已选择 {{ selectedFiles.length }} / 9 张图片</p>

    <!-- 图片预览 -->
    <div v-if="selectedFiles.length > 0" class="preview-container">
      <div
        v-for="(file, index) in selectedFiles"
        :key="index"
        class="preview-item"
      >
        <img :src="file.previewUrl" :alt="file.name" />
        <button @click="removeFile(index)" class="remove-btn">×</button>
      </div>
    </div>

    <!-- 上传按钮 -->
    <button
      @click="uploadImages"
      :disabled="selectedFiles.length === 0 || uploading"
    >
      {{ uploading ? "上传中..." : "开始上传" }}
    </button>

    <!-- 上传进度 -->
    <div v-if="uploading">
      <p>上传进度: {{ uploadProgress }}%</p>
    </div>
  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      order: {}, //订单
      selectedFiles: [], // 存储选中的文件对象
      uploading: false, // 上传状态
      uploadProgress: 0, // 上传进度
    };
  },
  methods: {
    // 处理文件选择变化
    handleFileChange(event) {
      const newFiles = Array.from(event.target.files);
      const totalFiles = this.selectedFiles.length + newFiles.length;

      // 检查文件数量是否超过9张
      if (totalFiles > 9) {
        alert("最多只能上传9张照片！");
        return;
      }

      newFiles.forEach((file) => {
        // 可选：检查文件类型和大小
        if (!file.type.startsWith("image/")) {
          alert(`文件 ${file.name} 不是图片类型！`);
          return;
        }
        if (file.size > 3 * 1024 * 1024) {
          // 限制3MB
          alert(`文件 ${file.name} 太大了！请选择小于3MB的图片。`);
          return;
        }

        // 创建预览URL
        const previewUrl = URL.createObjectURL(file);
        this.selectedFiles.push({ file, previewUrl });
      });

      // 清空input的值，允许重复选择同一文件
      event.target.value = "";
    },

    // 移除已选文件
    removeFile(index) {
      // 释放预览URL的内存
      URL.revokeObjectURL(this.selectedFiles[index].previewUrl);
      this.selectedFiles.splice(index, 1);
    },

    // 上传图片
    async uploadImages() {
      if (this.selectedFiles.length === 0) return;

      this.uploading = true;
      this.uploadProgress = 0;

      const formData = new FormData();
      // 将所有文件添加到FormData中
      this.selectedFiles.forEach((selectedFile) => {
        formData.append("files", selectedFile.file);
      });

      try {
        const response = await axios.post(
          "http://localhost/8888/playmate/publishOrder",
          formData,
          {
            headers: {
              "Content-Type": "multipart/form-data",
            },
            onUploadProgress: (progressEvent) => {
              if (progressEvent.total) {
                this.uploadProgress = Math.round(
                  (progressEvent.loaded * 100) / progressEvent.total
                );
              }
            },
          }
        );

        console.log("上传成功:", response.data);
        alert("所有照片上传成功！");
        // 上传成功后清空已选文件
        this.selectedFiles.forEach((file) =>
          URL.revokeObjectURL(file.previewUrl)
        );
        this.selectedFiles = [];
      } catch (error) {
        console.error("上传失败:", error);
        alert("上传失败，请重试！");
      } finally {
        this.uploading = false;
        this.uploadProgress = 0;
      }
    },
  },
  // 组件销毁前清理预览URL，避免内存泄漏
  beforeDestroy() {
    this.selectedFiles.forEach((file) => URL.revokeObjectURL(file.previewUrl));
  },
};
</script>

<style scoped>
.preview-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin: 15px 0;
}
.preview-item {
  position: relative;
  width: 100px;
  height: 100px;
}
.preview-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}
.remove-btn {
  position: absolute;
  top: -5px;
  right: -5px;
  background: red;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  cursor: pointer;
}
</style>
